package JasPerl::Util::Cookie;

use strict;
use warnings;

use Scalar::Util qw(blessed);

my %COERCIONS = (
    'CGI::Cookie' => sub {
        my ($class, $from) = @_;
        my $self = $class->JasPerl::Util::Cookie::new($from->name, $from->value);
        $self->set_domain($from->domain);
        $self->set_max_age($from->max_age);
        $self->set_path($from->path);
        $self->set_secure($from->secure);
        $self->set_http_only($from->httponly);
        return $self;
    },
    'CGI::Simple::Cookie' => sub {
        my ($class, $from) = @_;
        my $self = $class->JasPerl::Util::Cookie::new($from->name, $from->value);
        $self->set_domain($from->domain);
        $self->set_max_age($from->max_age);
        $self->set_path($from->path);
        $self->set_secure($from->secure);
        $self->set_http_only($from->httponly);
        return $self;
    }
);

sub new {
    my ($class, $name, $value) = @_;

    bless {
        name => $name,
        value => $value,
        maxage => -1,
        version => 0
    }, $class;
}

sub from {
    my ($class, $from) = @_;
    # $class->parse handles undef
    return $class->parse($from) unless ref $from;

    if (blessed $from) {
        return $from if $from->isa($class);

        foreach my $type (keys %COERCIONS) {
            return $COERCIONS{$type}->($class, $from) if $from->isa($type);
        }
    }

    JasPerl::Util::CoercionException->throw(
        "Cannot create $class from " . (ref $from || 'scalar')
    );
}

sub clone {
    bless { %{$_[0]} }, ref $_[0];
}

sub set_comment {
    $_[0]->{comment} = $_[1];
}

sub get_comment {
    return $_[0]->{comment};
}

sub set_domain {
    $_[0]->{domain} = $_[1];
}

sub get_domain {
    return $_[0]->{domain};
}

sub set_max_age {
    $_[0]->{'max-age'} = $_[1];
}

sub get_max_age {
    return $_[0]->{'max-age'};
}

sub set_path {
    $_[0]->{path} = $_[1];
}

sub get_path {
    return $_[0]->{path};
}

sub set_secure {
    $_[0]->{secure} = $_[1];
}

sub get_secure {
    return $_[0]->{secure};
}

sub get_name {
    return $_[0]->{name};
}

sub set_value {
    $_[0]->{value} = $_[1];
}

sub get_value {
    return $_[0]->{value};
}

sub set_version {
    $_[0]->{version} = $_[1];
}

sub get_version {
    return $_[0]->{version};
}

sub set_http_only {
    $_[0]->{httponly} = $_[1];
}

sub is_http_only {
    return $_[0]->{httponly};
}

sub as_hash {
    return %{$_[0]};
}

1;
